package base

import (
	"github.com/gin-gonic/gin"
	logging "github.com/sirupsen/logrus"
	"net/http"
)

// 全局异常处理
func Recover(ctx *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			//打印错误堆栈信息
			logging.Error("global error is ", err)
			response := FailedResponse(http.StatusInternalServerError, errorToString(err))
			ctx.JSON(http.StatusInternalServerError, response)
			//终止后续接口调用，不加的话recover到异常后，还会继续执行接口里后续代码
			ctx.Abort()
		}
	}()
	//加载完 defer recover，继续后续接口调用
	ctx.Next()
}

// recover错误，转string
func errorToString(err interface{}) string {
	switch err := err.(type) {
	case error:
		return err.Error()
	default:
		return err.(string)
	}
}
